<?php

/**
 * @filename common.php 
 * @encoding UTF-8 
 * @author nemo.xiaolan <a href="mailto:335454250@qq.com">335454250@qq.com</a>
 * @link <a href="http://www.sep-v.com">http://www.sep-v.com</a>
 * @license http://www.sep-v.com/code-license
 * @datetime 2013-11-17 10:35:33
 * @descriptiont
 * 
 */
function makeBillCode() {
    $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $order_sn = $year_code[intval(date('Y')) - 2010] .
            strtoupper(dechex(date('m'))) . date('d') .
            substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%d', rand(0, 99));
    return $order_sn;
}

function getUserCache() {
    $userData = F("User/All");
    if (!$userData) {
        $tmp = D("User")->select();
        foreach ($tmp as $v) {
            unset($v["password"]);
            $userData[$v["id"]] = $v;
        }
        F("User/All", $userData);
    }
    return $userData;
}

function getUserTruenameArray() {
    $users = getUserCache();
    foreach($users as $k=>$v) {
        $users[$k] = $v["truename"];
    }
    return $users;
}

function getCurrentUid() {
    return $_SESSION["user"]["id"];
}

function toDate($str, $format = "Y-m-d H:i:s") {
    return date($format, $str);
}

function toUsername($uid) {
    if (!$uid) {
        return L("Unnamed");
    }
    $userData = getUserCache();
    return $userData[$uid]["username"];
}

function toTruename($uid) {
    if (!$uid) {
        return "";
    }
    
    $uids = explode(",", $uid);
    $userData = getUserCache();
    foreach($uids as $u) {
        if(!$u or !$userData[$u]["truename"]) {
            continue;
        }
        $names[] = $userData[$u]["truename"];
    }
    return implode(",", $names);
}

function inExplodeArray($id, $ids, $split=",") {
    return in_array($id, explode($split, $ids));
}

function toCustomerName($customerId) {
    return toRelCompanyName($customerId);
}

function toSupplierName($id) {
    return toRelCompanyName($id);
}

function toRelCompanyName($id) {
    $data = F("RelationshipCompany/All");
    if (!$data) {
        $model = D("RelationshipCompany");
        $tmp = $model->select();
        foreach ($tmp as $v) {
            $data[$v["id"]] = $v["name"];
        }
        F("RelationshipCompany/All", $data);
    }
    return $data[$id];
}

function clearCache($type = 0, $path = NULL) {
    if (is_null($path)) {
        switch ($type) {
            case 0:// 模版缓存目录
                $path = CACHE_PATH;
                break;
            case 1:// 数据缓存目录
                $path = TEMP_PATH;
                break;
            case 2:// 日志目录
                $path = LOG_PATH;
                break;
            case 3:// 数据目录
                $path = DATA_PATH;
                break;
        }
    }
//    import("ORG.Io.Dir");
    $rs = delDirAndFile($path);
}

function delDirAndFile($dirName) {
    if ($handle = opendir("$dirName")) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..") {
                if (is_dir("$dirName/$item")) {
                    delDirAndFile("$dirName/$item");
                } else {
                    @ unlink("$dirName/$item");
                }
            }
        }
        @ closedir($handle);
        @ rmdir($dirName);
    }
}


function makeDBConfigCache() {
    $config = F("Config/DB");
    if (!$config) {
        $model = D("Config");
        $tmp = $model->select();
        foreach ($tmp as $v) {
            $config[$v["alias"]] = $v["value"];
        }
    }
    return $config;
}

/**
 * 统一处理的类型
 * **/
function getTypes($type) {
    $types = F("Types");
    if(!$types) {
        $tmp = D("Types")->order("listorder DESC,id ASC")->select();
        foreach($tmp as $v) {
            $types[$v["type"]][] = $v;
        }
        F("Types", $types);
    }
    return $types[$type];
}

function getTypesIndex($type, $idField="id", $field="name") {
    $types = getTypes($type);
    foreach($types as $k=>$v) {
        $tmp[$v[$idField]] = $v[$field];
    }
    return $tmp;
}
function getTypeByAlias($type, $alias) {
    $types = getTypes($type);
    foreach($types as $t) {
        if($t["alias"] == $alias) {
            return $t;
        }
    }
}
function getTypeIdByAlias($type, $alias) {
    $types = getTypes($type);
    foreach($types as $t) {
        if($t["alias"] == $alias) {
            return $t["id"];
        }
    }
}


function toTypeName($id) {
    $types = F("TypesIndexArray");
    if(!$types) {
        $tmp = D("Types")->select();
        foreach($tmp as $v) {
            $types[$v["id"]] = $v["name"];
        }
        F("TypesIndexArray", $types);
    }
    return $types[$id];
}

function getTypesCategory() {
    return array(
        "purchase" => L("purchase_type"),
        "sale" => L("sale_type"),
        "returns"  => L("returns_type"),
        "shipment" => L("shipment_type"),
        "freight" => L("freight_type"),
        "pay" => L("pay_type"),
        "receive" => L("receive_type"),
        "voucher" => L("voucher_type")
    );
}
function toTypesCategory($alias) {
    $types = getTypesCategory();
    return $types[$alias];
}

function DBC($name) {
    $config = makeDBConfigCache();
    return $config[$name];
}

function getPwd($source) {
    return md5($source);
}

function getFactoryCodeAll($params) {
    list($fcid, $colorid, $standardid) = $params;
    return implode("-", $params);
}

function extraFactoryCodeAll($factory_code_all) {
    list($fcid, $colorid, $standardid) = explode("-", $factory_code_all);
    $data = array(
        "factory_code" => $fcid,
        "color_id" => $colorid,
        "standard_id" => $standardid
    );
    return $data;
//    print_r($data);exit;
}

/**
 * 仓库列表
 */
function getStocks($include_null=false) {
    $stocks = F("Stock/List");
    if (!$stocks) {
        $model = D("Stock");
        $stocks = $model->select();
        $stocks = $model->getIndexArray($stocks);
        F("Stock/List", $stocks);
    }
    if($include_null) {
        $stocks = array_merge(array(L("all")), $stocks);
    }
    return $stocks;
}



function getCategoryTree($model, $pid=1) {
    $cat = D($model);
    $data = $cat->getTree($pid);
    foreach($data as $k=>$t) {
        $data[$k]["prefix_name"] = $t["prefix"].$t["name"];
    }
    return $cat->getIndexArray($data, "prefix_name");
}

function toStockName($id) {
    $stocks = getStocks();
    return $stocks[$id];
}

function checkStoreNum($factory_code_all, $num, $stock_id = "") {
    $model = D("StockProductList");
    $map = array(
        "factory_code_all" => $factory_code_all
    );
    if($stock_id) {
        $map["stock_id"] = $stock_id;
    }
    $data = $model->where($map)->find();
    return $data["num"] >= $num;
}

/**
 * 生成日期序列
 */
function makeDateRange($start, $end, $step, $format = "m-d") {
    $tmp = range($start, $end, $step);
//    echo "<pre>";
//    echo $start;
//    echo "<br />";
//    echo $end;
//    echo "<br />";
//    echo $step;
//    var_dump($tmp);
    foreach ($tmp as $v) {
        $dateRange[] = date($format, $v);
    }
    return $dateRange;
}

function ksortHaveNoIndex($data) {
    foreach ($data as $v) {
        $tmp[] = $v;
    }
    return $tmp;
}

function array_sort($arr, $keys, $type = 'asc') {
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


/**
 * toForm
 * **/
function toForm($module, $action=null, $onlyFields=false, $data=array(), $groupname=GROUP_NAME) {
    import("@.Form.Form");
    $form = new Form($module, $action, $groupname);
    return $form->makeForm($action, $data, $onlyFields);
}
function toField($type, $value=null,$attr="") {
    $type = ucfirst($type);
    $file = "@.Form.Fields.".$type."Field";
    import($file);

    $fieldClassName = $type."Field";
    if(!class_exists($fieldClassName)) {
        return;
    }
    $fieldClass = new $fieldClassName();
    $fieldClass->fieldTemplate = "%s%s";
    
    $fieldsDefine = array();
    if($value) {
        $fieldsDefine["value"] = $value;
    }
    foreach(explode("&", $attr) as $v) {
        list($a,$va) = explode("=", $v);
        $fieldsDefine[$a] = $va;
    }
    
    $html = $fieldClass->makeHTML("", $fieldsDefine);
    if($fieldClass->endHTML) {
        return $html.$fieldClass->endHTML;
    }
}


function toGoodsCategoryName($catid) {
    return D("GoodsCategory")->where("id=".$catid)->getField("name");
}
function toDepartmentName($pid) {
    return D("Department")->where("id=".$pid)->getField("name");
}

function isModuleEnabled($moduleName) {
    return in_array($moduleName, C("ENABLED_MODULE"));
}

function getRegionPath($id) {
    
    $regions = F("Regions");
    if(!$regions) {
        $regionModel = D("Region");
        $tmp = $regionModel->order("listorder DESC,id ASC")->select();
        foreach($tmp as $v) {
            $regions[$v["id"]] = array(
                "id" => $v["id"],
                "pid" => $v["pid"],
                "name"=> $v["name"]
            );
        }
        F("Regions", $regions);
    }
    
    //town
    $town = $regions[$id];
    $city = $regions[$town["pid"]];
    $province = $regions[$city["pid"]];
    
    $data = array(
        "province" => $province, 
        "city" => $city, 
        "town" => $town
    );
    
//    print_r($data);exit;
    return $data;
}

function toRegionPath($id, $split=" ") {
    $regions = getRegionPath($id);
    return $regions["province"]["name"].$split.$regions["city"]["name"].$split.$regions["town"]["name"];
}

function getFinanceAccount() {
    $account = F("FinanceAccount");
    if(!$account) {
        $tmp = D("FinanceAccount")->order("listorder DESC")->select();
        foreach($tmp as $v) {
            $account[$v["id"]] = $v["name"];
        }
        F("FinanceAccount", $account);
    }
    return $account;
}

function toAccountName($id) {
    $account = getFinanceAccount();
    return $account[$id];
}
function toFinanceRecordType($type) {
    return $type == 1 ? L("fund_input") : L("fund_output");
}

function toYesOrNo($data) {
    return L($data ? "yes": "no");
}

function getWorkflowNodesStatus($alias, $include_null=false) {
    $workflow = D("Workflow")->getByAlias($alias);
    $nodes = D("WorkflowNode")->where("workflow_id=".$workflow["id"])->order("listorder ASC")->select();
//    echo D("WorkflowNode")->getLastSql();exit;
    foreach($nodes as $n) {
        $data[$n["id"]] = $n["status_text"];
    }
//    print_r($data);exit;
    if($include_null) {
        $data = array_merge(array(L("all")), $data);
    }
    return $data;
}

function toStatusText($status) {
    return $status == 0 ? L("ineffective") : L("effective");
}

function displayCheckNumHTML($param) {
    if($param["num"] > $param["store_num"]) {
        return sprintf('<span class="label label-warning" title="%s">%s</span>', L("store_num_not_full"), $param["num"]);
    } else {
        return $param["num"];
    }
}

function getFinanceAccountingSubjectCategory() {
    return array(
        "流动资产","非流动资产",
        "流动负债","非流动负债",
        "所有者权益",
        "成本",
        "营业收入","其他收益","营业成本及税金","其他损失","期间费用"
    );
}
function toFinanceAccountingSubjectCatetgory($id) {
    $cats = getFinanceAccountingSubjectCategory();
    return $cats[$id];
}
function toFinanceAccountingSubjectDirection($id) {
    if($id < 0) {
        return;
    }
    return $id ? "贷" : "借";
}
function getFinanceSubjectTypes() {
    return array(
        "资产", "负债", "所有者权益", "成本", "损益"
    );
}
function toFinanceSubjectType($id) {
    $subjects = getFinanceSubjectTypes();
    return $subjects($id);
}
function toFinanceAccountingSubject($id) {
    $vo = D("AccountingSubject")->find($id);
    return $vo["name"];
}

function toAccountingSubjectName($id) {
    $tmp = D("AccountingSubject")->find($id);
    return $tmp["name"];
}